﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using Coding4Fun.Phone.Controls;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using wordroid.Model;
using wordroid.Resources;
using wordroid.ViewModel;
using wordroid.utils;
using wordroid.utils.http;

namespace wordroid {
    
    public partial class MainPage : PhoneApplicationPage {
        
        public MainPage() {
            InitializeComponent();
            LocalesPicker.ItemsSource = Constants.TTS_LOCALES;
            helper = DBHelper.getInstance();            
            wordsManagerListBox.ItemsSource = helper.Words;
        }

        private void WordsCountTextBox_KeyDown(object sender, KeyEventArgs e) {
            //numeric and backspace filter
            if (Array.IndexOf(Constants.numeric, e.Key) == -1) {
                e.Handled = true;
            }
        }

        private void StartTrainingClick(object sender, RoutedEventArgs e) {

            int wordsCount;
            if(!int.TryParse(WordsCountTextBox.Text, out wordsCount)) {
                wordsCount = 0;
            }

            string locale = LocalesPicker.Items[LocalesPicker.SelectedIndex].ToString();
            NavigationService.Navigate(new Uri(string.Format(Constants.TrainingUrl, wordsCount, locale), UriKind.Relative));
        }

        private void pivot_LoadingPivotItem(object sender, PivotItemEventArgs e) {
            if (e.Item == WordsManagerPivot) {
                WordManagerAppBar.IsVisible = true;
                ApplicationBar = WordManagerAppBar;
            } else {
                WordManagerAppBar.IsVisible = false;
            }
        }

        private ApplicationBar WordManagerAppBar { 
            get {
                return (ApplicationBar)Resources["WordsManagerAppBar"];
            }
        }

        private void CreateWord_click(object sender, EventArgs e) {
            PhoneApplicationFrame root = Application.Current.RootVisual as PhoneApplicationFrame;

            if (root != null) {
                root.Navigate(new Uri(Constants.CreateWordUrl, UriKind.Relative));
            }
        }

        private void RWMStartDownloadButton_Click(object sender, RoutedEventArgs e) {

            String un = RWMUserNameTextBox.Text;
            String password = RWMPasswordBox.Password;

            if (String.IsNullOrWhiteSpace(un) || String.IsNullOrWhiteSpace(password)) {
                new Prompt {
                    Message = AppResources.ErrorUnPwdEmpty,
                }.Show();
                return;
            }

            RWMStartDownloadButton.IsEnabled = false;

            download(un, password);
        }

        private void download(String un, String pwd) {

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("un", un);
            parameters.Add("pwd", pwd);
            parameters.Add("act", "act"); //todo remove later. ruby site should be fixed

            PostClient proxy = new PostClient(parameters);
            
            proxy.DownloadStringCompleted += (sender, e) => {
                if (e.Error == null) {
                    
                    XMLParser.LoadAndsave(e.Result, new EventHandler((o, args) => {
                            DownloadManagerEventArgs dmargs = (args as DownloadManagerEventArgs);
                            if(dmargs.Success) {
                                new Prompt { Message = AppResources.MessageDownloadFinished }.Show();
                            } else {
                                new Prompt { Message = AppResources.ErrorParsingError }.Show();
                            }
                            RWMStartDownloadButton.IsEnabled = true;
                    }));
                } else {
                    new Prompt { Message = AppResources.ErrorConnectionError }.Show();
                    RWMStartDownloadButton.IsEnabled = true;
                }
            };

            new Prompt { Message = AppResources.MessageDownloadStarted }.Show();
            proxy.DownloadStringAsync(new Uri(Constants.SiteUrl, UriKind.Absolute));            
        }

        private readonly DBHelper helper;
    }

    internal class Prompt : ToastPrompt {
        public Prompt() {
            FontSize = 30;
            TextOrientation = System.Windows.Controls.Orientation.Horizontal;
        }
    }
}